/* eslint-disable no-mixed-spaces-and-tabs */
const express = require('express');
const router = express.Router();
const svgCaptcha = require('svg-captcha');
const ManagerModel = require('../../model/managerModel');
const md5 = require('md5');
router.get("/",(req,res)=>{
	// let result = new ManagerModel({
	// 	username:"admin",
	// 	password:md5("123456"),
	// })
	// result.save((err,data)=>{
	// 	if(err){
	// 		console.log(err);
	// 		return;
	// 	}
	// 	console.log(data)
		
	// })
  res.render("admin/login/login.html");
})

router.post("/doLogin",(req,res)=>{
	// eslint-disable-next-line no-unused-vars
	let {username,password,verify} = req.body;
	//1.判断验证码是否正确
	if(verify.toLocaleLowerCase() != req.session.captcha.toLocaleLowerCase()){
		res.render("admin/public/error.html",{
			redirectUrl:`/${req.app.locals.adminPath}/login`,
			message:"验证码错误"
		})
		return;
	}
	//2.判断用户名和密码是否合法
	ManagerModel.find({username,password:md5(password)},(err,data)=>{
		if(err){
			console.log(err)
			return;
		}
		console.log(data)
		if(data.length == 0){
			res.render("admin/public/error.html",{
				redirectUrl:`/${req.app.locals.adminPath}/login`,
				message:"用户名或密码错误"
			})
		}else{
			console.log(data)
			req.session.userInfo = data[0];
			res.render("admin/public/success.html",{
				redirectUrl:`/${req.app.locals.adminPath}/`,
				message:"登录成功"
			})
		}
	
	})

})

//生成验证码
router.get('/verify', function (req, res) {
	var captcha = svgCaptcha.create();
	//保存验证码到session
	req.session.captcha = captcha.text;
	
	res.type('svg');
	res.status(200).send(captcha.data);
});

//退出登录
router.get('/loginOut', function (req, res) {
	req.session.userInfo = null;//清除用户session然后跳转到登录页面
	res.redirect(`/${req.app.locals.adminPath}/login`);
});
module.exports = router